package com.pronhub.cloud.shop.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {
    public static final String TOKEN_NAME = "userToken";
    public static final int TOKEN_SECONDS = 1800;
    /**
     * 给浏览器设置响应时间
     * @param response 浏览器
     * @param cookieName 名字:token
     * @param cookieValue 就是UUID的一坨
     * @param expireSecond 存活时间
     */
    public static void addCookie(HttpServletResponse response,String cookieName,
                                 String cookieValue,int expireSecond){
        Cookie cookie = new Cookie(cookieName,cookieValue);
        cookie.setDomain("localhost");
        cookie.setPath("/");
        cookie.setMaxAge(expireSecond);
        response.addCookie(cookie);
    }


    public static String getCookie(HttpServletRequest request, String tokenName) {
        //从request里面获取Cookie
        Cookie[] cookies = request.getCookies();
        if (cookies!=null && cookies.length>0){
            for(Cookie cookie:cookies){
                if(cookie.getName().equals(tokenName)){
                    //找到需要的cookie
                    return cookie.getValue();
                }
            }
        }

        return null;
    }
}
